<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增销售订单')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <h4 class="col-sm-12 form-header h4">销售订单信息 &nbsp;&nbsp;&nbsp; 订单号：<span id="orderId" th:text="${orderId}" style="font-size: 15px"></span></h4>
        <form>
        <div class="row col-sm-12">
            <div class="select-list col-sm-8" id="userWorker">
                <ul>
                    <li>
                        <label class="text-center" >水电师傅：</label>
                    </li>
                    <li>
                        <select class="workerChoose form-control" onchange="workerChange()"><option value="">单击选择</option></select>
                    </li>
                    <li>
                        <label class="text-center">客户名称：</label>
                    </li>
                    <li>
                        <select class="userChoose form-control" onchange="getUserPhone()"><option value="">单击选择</option></select>
                    </li>
                    <li>
                        <label class="text-center">联系方式：</label>
                    </li>
                    <li>
                        <input class="form-control" type="text" id="phoneNumber">
                    </li>
                </ul>
            </div>
            <div class="col-sm-4 text-center">
                <button class="btn btn-primary dim" type="button" onclick="saveClose();"><i class="fa fa-calendar-check-o"></i>&nbsp;保存关闭</button>
            </div>
        </div>
        <div class="row col-sm-12">
            <div class="select-list col-sm-8">
                <ul>
                    <li>
                        <label class="text-center" >开单时间：</label>
                    </li>
                    <li>
                        <input type="text" id="orderDate" th:value="${#dates.format(new java.util.Date(), 'yyyy-MM-dd')}">
                    </li>
                    <li>
                        <label class="text-center">备注说明：</label>
                    </li>
                    <li>
                        <input class="remark form-control" type="text">
                    </li>
                    <li>
                        <label class="text-center">&nbsp;</label>
                    </li>
                    <li>
                        <button type="button" class="btn btn-dark" onclick="userAdd()"><i class="fa fa-plus"> 新增客户</i></button>
                    </li>
                </ul>
            </div>
            <div class="col-sm-4 text-center">
                <button class="btn btn-success dim" type="button" onclick="orderPrint()"><i class="fa fa-print"></i>&nbsp;打印预览</button>
            </div>
        </div>
        </form>
        <div class="form-group"></div>
        <h4 class="col-sm-12 form-header h4">销售订单明细信息</h4>
        <div class="row">
            <div class="col-sm-12">
                <form id="formId">
                    <div class="select-list">
                        <input type="hidden" name="orderId" th:value="${orderId}">
                        <ul>
                            <li>
                                <label>&nbsp;</label>
                                <button type="button" class="btn btn-success" onclick="addProduct()"><i class="fa fa-plus"> 添加商品</i></button>
                            </li>
                        </ul>
                    </div>
                </form>
                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: select2-js" />
    <th:block th:include="include :: jquery-cxselect-js" />
    <th:block th:include="include :: bootstrap-table-editable-js" />
    <script th:inline="javascript">

        var orderStatus = true;

        $(function(){
            layui.use('laydate', function(){
                var laydate = layui.laydate;
                laydate.render({
                    elem: '#orderDate',
                    type: 'date'
                });
            });
        });

        $(function() {
            var options = {
                url: ctx + "order/detail/list",
                removeUrl: ctx + "order/detail/remove",
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                modalName: "销售订单明细",
                onEditableSave: onEditableSave,
                columns: [
                {
                    field: 'odId',
                    title: '明细id',
                    visible: false
                },
                {
                    title: "序号",
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.serialNumber(index);
                    }
                },
                {
                    field: 'productName',
                    width: '20',
                    widthUnit: '%',
                    title: '商品名'
                },
                {
                    field: 'productBrand',
                    title: '品牌',
                    align: 'center'
                },
                {
                    field: 'productNum',
                    title: '数量',
                    align: 'center',
                    editable : {
                        type : 'text',
                        title : '数量',
                        emptytext : "1",
                        validate : function(value) {
                            if (value.length == 0) {
                                return '数量不能为空';
                            }
                            var num = /^[+-]?[0-9]+(\.[0-9]{1,2})?$/;
                            if(!num.test(value)){
                                return '必须为纯数字';
                            }
                            if (value == 0) {
                                return '数量不能为0';
                            }
                        }
                    }
                },
                {
                    field: 'productUnit',
                    title: '单位',
                    align: 'center',
                    editable : {
                        type : 'text',
                        title : '单位',
                        emptytext : '个'
                    }
                },
                {
                    field: 'detailPrice',
                    title: '单价',
                    align: 'center',
                    editable : {
                        type : 'text',
                        title : '金额',
                        emptytext : '0.00',
                        validate : function(value) {
                            var num = /^[+-]?[0-9]+(\.[0-9]{1,2})?$/;
                            if(!num.test(value)){
                                return '不符合金额规范，请重新输入';
                            }
                        }
                    }
                },
                {
                    field: 'detailAmount',
                    title: '金额',
                    align: 'center'
                },
                {
                    field: 'remark',
                    title: '备注',
                    align: 'center',
                    editable : {
                        type : 'text',
                        title : '备注',
                        emptytext : '添加备注'
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-danger btn-xs ' + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.odId + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
            $.table.search('formId', 'bootstrap-table');
        });

        //拉取师傅信息
        $(function () {
            $.ajax({
                type: "post",
                url: ctx + "hh/user/selectList",
                data: {
                    "roleId": 101,
                    "status": 0
                },
                success: function(result) {
                    if (result.code == 0) {
                        $('#userWorker').cxSelect({
                            required: false,
                            firstTitle: '单击选择',
                            selects: ['workerChoose'],
                            jsonName: 'name',
                            jsonValue: 'id',
                            data: result.data
                        });
                    }
                }
            })
        });

        //拉取客户信息
        function workerChange() {
            $.ajax({
                type: "post",
                url: ctx + "hh/user/selectList",
                data: {
                    "status": 0,
                    "workerId": $(".workerChoose").val()
                },
                success: function(result) {
                    if (result.code == 0) {
                        $('#userWorker').cxSelect({
                            required: true,
                            selects: ['userChoose'],
                            jsonName: 'name',
                            jsonValue: 'id',
                            data: result.data
                        });
                        $.table.refresh();
                    }
                }
            })
        }

        //根据用户信息获得联系方式
        function getUserPhone() {
            $.ajax({
                type: "post",
                url: ctx + "hh/user/userInfo",
                data: {
                    "userId": $(".userChoose").val(),
                    "workerId": $(".workerChoose").val()
                },
                success: function(result) {
                    if (result.code == 0) {
                        $("#phoneNumber").val(result.data.phonenumber);
                    }
                }
            })
        }

        //新增商品
        var selectLength = [[${selectLength}]];
        function addProduct() {
            var userId = $(".userChoose").val();
            var orderId = $("#orderId").text();
            if (userId == null || userId.length == 0) {
                $.modal.alertError("先选择客户，再添加商品！");
                return false;
            }
            if (selectLength == $('#bootstrap-table').bootstrapTable('getOptions').totalRows) {
                $.modal.alertError("本页已满！");
                return false;
            }
            //校验是否生成订单
            if (orderStatus) {
                $.ajax({
                    type: "post",
                    url: ctx + "order/manage/add",
                    data: {
                        "orderId": orderId,
                        "workerId": $(".workerChoose").val(),
                        "consumerId": userId,
                        "orderStatus": '0',
                        "orderType": '1',
                        "remark": $(".remark").val(),
                        "orderDate": $("#orderDate").val()
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            orderStatus = false;
                        }
                    }
                })
            }
            layer.open({
                type: 2,
                area: ['1100px', '700px'],
                fix: false,
                shade: 0.3,
                title: '添加商品',
                content: ctx + "order/detail/add/" + orderId,
                btn: [],
                end: function () {
                    $('.workerChoose').prop('disabled', true);
                    $('.userChoose').prop('disabled', true);
                    $('#orderDate').prop('disabled', true);
                    $('#phoneNumber').prop('disabled', true);
                    $('.remark').prop('disabled', true);
                    $.table.refresh();
                }
            });

        }

        //查找订单中的商品
        $("#productName").keyup(function () {
            $.table.search('formId', 'bootstrap-table');
        });

        //打印预览
        function orderPrint() {
            if(orderStatus){
                $.modal.alertError("还没有选择商品，请点击添加商品！");
                return false;
            }
            layer.open({
                type: 2,
                area: ['900px', '700px'],
                fix: false,
                title: '打印预览',
                content: ctx + "order/detail/print/" + $("#orderId").text() ,
                btn: ['关闭'],
                end: function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                }
            });
        }

        //保存关闭
        function saveClose() {
            if(orderStatus){
                $.modal.alertError("还没有选择商品，请点击添加商品！");
                return false;
            }
            var orderId = $("#orderId").text();
            $.ajax({
                type: "post",
                url: ctx + "order/detail/save",
                data: {
                    "orderId": orderId
                },
                success: function(result) {
                    if (result.code == 0) {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    }
                }
            })
        }

        //表格编辑保存
        function onEditableSave(field, row, rowIndex, oldValue, $el) {
            if (field == 'remark' || field == 'productUnit'){
                $.ajax({
                    type: "post",
                    url: ctx + "order/detail/edit",
                    data: {
                        "odId": row.odId,
                        "productUnit": row.productUnit,
                        "remark": row.remark
                    },
                    success: function(result) {
                        $.table.refresh();
                    }
                })
            }
            else {
                $.ajax({
                    type: "post",
                    url: ctx + "order/detail/edit",
                    data: {
                        "odId": row.odId,
                        "productId": row.productId,
                        "productNum": row.productNum,
                        "detailPrice": row.detailPrice
                    },
                    success: function(result) {
                        $.table.refresh();
                    }
                })
            }
        }

        /* 新增客户 */
        function userAdd() {
            layer.open({
                type: 2,
                area: ['600px', '500px'],
                fix: false,
                shade: 0.3,
                title: '新增客户',
                content: ctx + "hh/user/userAdd",
                btn: [],
                end: workerChange
            });
        }
    </script>
</body>
</html>